<?php
// 登录页面

require '../models/init.php';

function gotoPage($info){
    echo '<script>';
    echo "alert('{$info}');";
    echo 'window.history.back();';
    echo '</script>';
    exit; // 确保在跳转之后立即终止脚本的执行
}


// 登出
if(!empty($_GET)){
    if($_GET['loginout']==true){
        session_start(); // 开启会话
        session_unset(); // 清空Session变量
        session_destroy(); // 销毁Session

        setcookie("user_id", "", time() - 3600, "/"); // 设置过期时间为当前时间之前，使Cookie失效

        // 返回当前页面并刷新
        echo '<script>window.location.assign(document.referrer);</script>';
        exit;
    }
}

// 登录
if(!empty($_POST)){
    // var_dump($_POST);
    $regstae = true; //判断数据验证状态
    $msg = ''; //获取数据错误信息

    session_start();
    if (strtolower($_POST['key']) != strtolower($_SESSION['captcha'])) {
        $msg .= '验证码不正确';
        $regstae = false;
    }

    $data['username'] = trim($_POST['username']);
    $data['password'] = trim($_POST['password']);

    // 判断用户是否勾选了自动登录按钮
    if (isset($_POST['autologin'])) {
        $data['autologin'] = trim($_POST['autologin']);
    }

    //数据验证

    if ($data['username'] == '' || $data['password'] == '') {
        $msg .= '用户名或密码不能为空！';
        $regstae = false;
    }

    // 判断验证是否通过，不通过则提示并返回登录页
    if (!$regstae) {
        gotoPage($msg);
    }

    //批量防sql注入，处理特殊字符
    $link = db_connect();
 
    foreach ($data as $k => $v) {
        $data[$k] = str_handle($link, $v);
    }

    // 查询
    $res = mysqli_query($link, "SELECT * FROM `user` WHERE `username`='{$data['username']}'");
    
    if(mysqli_num_rows($res)==0){
        gotoPage('用户不存在！');
    }

    while($rs=mysqli_fetch_object($res)) {
        $salt = $rs->salt;

        //获取到一个加密后的密码串
        $dbpw = get_Password($data['password'], $salt);

        try {
            if ($rs->password != $dbpw) {
                throw new Exception("密码不正确，请重新输入。");
            } else if ($rs->state != 1) {
                throw new Exception("您的账号已锁定，状态不可用！");
            } else {
                // 判断用户是否勾选了自动登录，如果勾选了则设置cookie实现自动登录
                if ($data['autologin'] == 1) {
                    // 设置cookie 有效期为1小时
                    setcookie('user_id', $rs->uid, time() + 3600, '/');
                }

                // 通过session来持久化存储用户信息
                // 启动会话
                session_start();

                // 将用户信息存储在会话中
                $_SESSION['user_id'] = !empty($rs->uid) ? $rs->uid : null;
                $_SESSION['user_name'] = !empty($rs->username) ? $rs->username : null;
                $_SESSION['true_user_name'] = !empty($rs->truename) ? $rs->truename : null;
                $_SESSION['user_email'] = !empty($rs->email) ? $rs->email : null;
                $_SESSION['user_phone'] = !empty($rs->phone) ? $rs->phone : null;
                $_SESSION['user_state'] = !empty($rs->state) ? $rs->state : null;

                header("Location: /index.php");
                exit;
            }
        } catch (Exception $e) {
            gotoPage($e->getMessage());
        } finally {
            mysqli_close($link);
        }
    }
}